package com.quan.commons.config.wx;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.common.collect.Maps;
import com.quan.commons.utils.SpringContextHolder;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties(WxPayProperties.class)
@AllArgsConstructor
public class WxPayConfiguration {

    @Autowired
    private WxPayProperties properties;

    private static Map<String, WxPayService> maServices = Maps.newHashMap();


    public static WxPayService getPayService(String appid) {
        WxPayService wxService = maServices.get(appid);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        return wxService;
    }

    public static WxPayProperties.Config getAppIdConfig(String appid) {
        final WxPayProperties properties = SpringContextHolder.getBean(WxPayProperties.class);
        List<WxPayProperties.Config> configs = properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("未添加下相关配置，注意别配错了！");
        }

        final List<WxPayProperties.Config> collect = configs.stream().filter(s -> s.getAppId().equals(appid)).collect(Collectors.toList());

        if (null != collect) {
            return collect.get(0);
        } else {
            return null;
        }
    }

    @PostConstruct
    public void init() {
        List<WxPayProperties.Config> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("未添加下相关配置，注意别配错了！");
        }

        maServices = configs.stream().map(a -> {
            WxPayConfig config = new WxPayConfig();

            config.setAppId(a.getAppId());
            config.setMchId(a.getMchId());
            config.setMchKey(a.getMchKey());
            config.setKeyPath(a.getKeyPath());

            WxPayService service = new WxPayServiceImpl();
            service.setConfig(config);
            return service;
        }).collect(Collectors.toMap(s -> s.getConfig().getAppId(), a -> a));
    }

}
